﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using quinielonModel;
using Facebook;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var fbCodeGiven = Request["code"];
        string getAccessToken = "";
        quinielonEntities db = new quinielonEntities();

        if (fbCodeGiven != null)
        {
            var fbApp = Utils.getAppInfo();
            var fb = new FacebookClient();
            dynamic result = fb.Get("oauth/access_token", new
            {
                client_id = fbApp.appId,
                client_secret = fbApp.appSecret,
                redirect_uri = "http://localhost:1730/Des/home.aspx",
                //redirect_uri = "http://chiquiniela.skan4labs.com/home.aspx",
                code = fbCodeGiven
            });

            fb = new FacebookClient(result["access_token"]);
            var user = (IDictionary<string, object>)fb.Get("/me");
            Label1.Text = (string)user["name"];
            string FBUID = (string)user["id"];

            //Comprobar si existe en la BBDD

            usuario usuario = (from u in db.usuario where u.id_fb.Equals(FBUID) select u).FirstOrDefault();
            //Si no existe se mete en la BBDD
            if (usuario == null)
            {
                usuario nuevoUsuario = new usuario();
                nuevoUsuario.id_fb = FBUID;
                nuevoUsuario.token = getAccessToken;
                nuevoUsuario.email = (string)user["email"];
                db.AddTousuario(nuevoUsuario);
                Session["user"] = nuevoUsuario;
                usuario = nuevoUsuario;
            }


            Session["user"] = usuario;
            Session["userFB"] = user;



            //Entrada en el log
            usuariosLog newUserAPISettings = new usuariosLog();
            newUserAPISettings.fb_date_connected = DateTime.UtcNow;
            newUserAPISettings.fb_session = getAccessToken;
            newUserAPISettings.fb_user_id = long.Parse((string)user["id"]);
            newUserAPISettings.email = (string)user["email"];

            db.AddTousuariosLog(newUserAPISettings);
            db.SaveChanges();

        }
        db.Dispose();
    }
}